package dimension.starry.dataManager;

import dimension.starry.StarryDimension;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.world.PersistentState;
import net.minecraft.world.PersistentStateManager;
import net.minecraft.world.World;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DataManager extends PersistentState {

    private final Map<String, NbtCompound> nbtMap;

    public DataManager() {
        this.nbtMap = new ConcurrentHashMap<>();
    }

    public DataManager(Map<String, NbtCompound> nbtMap) {
        this.nbtMap = nbtMap;
    }

    public static NbtCompound getNbt(ServerWorld world, String key) {
        return get(world.getServer()).nbtMap.get(key);
    }

    public static void setNbt(ServerWorld world, String key, NbtCompound value) {
        get(world.getServer()).setNbt(key, value);
    }

    public static DataManager createFromNbt(NbtCompound nbt) {
        Map<String, NbtCompound> nbtMap = new ConcurrentHashMap<>();
        nbt.getKeys().forEach(key -> nbtMap.put(key, nbt.getCompound(key)));
        return new DataManager(nbtMap);
    }

    public static DataManager get(MinecraftServer minecraftServer) {
        PersistentStateManager persistentStateManager = minecraftServer.getOverworld().getPersistentStateManager();
        DataManager dataManager = persistentStateManager.getOrCreate(
            DataManager::createFromNbt, DataManager::new, StarryDimension.MOD_ID);
        dataManager.markDirty();
        return dataManager;
    }

    @Override
    public NbtCompound writeNbt(NbtCompound compound) {
        nbtMap.forEach(compound::put);
        return compound;
    }

    private void setNbt(String key, NbtCompound value) {
        this.nbtMap.put(key, value);
        this.setDirty(true);
    }

}
